package cn.tedu.hotel.serve.service.impl;

import cn.tedu.hotel.serve.ex.ServiceException;
import cn.tedu.hotel.serve.mapper.*;
import cn.tedu.hotel.serve.pojo.dto.HotelCurrentRoomsDTO;
import cn.tedu.hotel.serve.pojo.dto.OrdersDTO;
import cn.tedu.hotel.serve.pojo.entity.HotelOrdersCount;
import cn.tedu.hotel.serve.pojo.entity.HotelRoomNotes;
import cn.tedu.hotel.serve.pojo.entity.OrderState;
import cn.tedu.hotel.serve.pojo.entity.Orders;
import cn.tedu.hotel.serve.pojo.vo.*;
import cn.tedu.hotel.serve.service.IOrdersService;
import cn.tedu.hotel.serve.web.ServiceCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

@Slf4j
@Service
public class OrdersServiceImpl implements IOrdersService {

    @Autowired
    OrdersMapper ordersMapper;

    @Autowired
    UserMapper userMapper;

    @Autowired
    HotelMapper hotelMapper;

    @Autowired
    OrderStateMapper orderStateMapper;

    @Autowired
    HotelOrdersCountMapper hotelOrdersCountMapper;

    @Override
    public void addOrder(OrdersDTO ordersDTO) {
        log.debug("开始处理【前台增加订单】的业务，参数：{}", ordersDTO);
        UserStandardVO standardVO = userMapper.getStandardById(ordersDTO.getUserId());
        if (standardVO == null) {
            String message = "订单增加失败，用户不存在，非法增加订单！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERROR_CONFLICT, message);
        }
        LocalDateTime checkInTime = ordersDTO.getCheckInTime();
        if (checkInTime == null) {
            String message = "登入时间不存在，增加订单失败！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERROR_CONFLICT, message);
        }
        LocalDateTime departureTime = ordersDTO.getDepartureTime();
        if (departureTime == null) {
            String message = "离店时间不存在，增加订单失败！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERROR_CONFLICT, message);
        }
        Orders order = new Orders();
        /*给日期赋入住时间和离店时间*/
        LocalDateTime newCheckInTime = ordersDTO.getCheckInTime().plusHours(CHECK_IN_TIME_HOURS);
        LocalDateTime newDepartureTime = ordersDTO.getDepartureTime().plusHours(Departure_TIME_HOURS);

        BeanUtils.copyProperties(ordersDTO, order);
        /*根据酒店ID和房间ID查询酒店房间信息表中的数据*/
        order.setCheckInTime(newCheckInTime);
        order.setDepartureTime(newDepartureTime);

        HotelRoomInfoVO hotelRoomInfoByHotelIdAndRoomId =
                hotelMapper.getHotelRoomInfoByHotelIdAndRoomId(ordersDTO.getHotelId(), ordersDTO.getRoomId());
        log.debug("根据酒店ID和房间ID查询酒店房间信息表中的数据:{}", hotelRoomInfoByHotelIdAndRoomId);
        /*计算住宿天数*/
        Duration duration = Duration.between(ordersDTO.getCheckInTime(), ordersDTO.getDepartureTime());
        long days = duration.toDays();
        log.debug("计算住宿天数:{}", days);
        /*计算总价*/
        BigDecimal bigDays = new BigDecimal(days);
        BigDecimal rooms = new BigDecimal(ordersDTO.getCountOfBuyRooms());
        BigDecimal price = bigDays.multiply(rooms.multiply(hotelRoomInfoByHotelIdAndRoomId.getPrice()));
        order.setOrderPrice(price);
        /*设定订单创建时间*/
        order.setCreateTime(LocalDateTime.now());

        List<LocalDateTime> list = new ArrayList<>();

        for (long i = 0; i < days; i++) {
            LocalDateTime localDateTime = order.getCheckInTime().plusDays(i);
            list.add(localDateTime);
        }
        log.debug("客户住宿的日期：{}", list);
        for (LocalDateTime localDateTime : list) {
            HotelRoomNotesVO singleNotesByThreeColumn = ordersMapper.getSingleNotesByThreeColumn(
                    order.getHotelId(), order.getRoomId(), localDateTime
            );
            if (singleNotesByThreeColumn == null) {
                continue;
            }
            if (order.getCountOfBuyRooms() > singleNotesByThreeColumn.getRemainder()) {
                String message = "您预订的房间数量超出可预订范围，请重新选择！";
                log.warn(message);
                throw new ServiceException(ServiceCode.ERROR_BAD_REQUEST, message);
            }
        }

        log.debug("计算总价:{}", price);
        int rows = ordersMapper.addOrder(order);
        if (rows != 1) {
            String message = "服务器繁忙，请稍后重试！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERROR_INSERT, message);
        }
        /*往订单状态表中添加支付状态*/
        OrderState orderState=new OrderState();
        orderState.setUsername(order.getUsername());
        orderState.setUserId(order.getUserId());
        orderState.setOrderId(order.getId());
        orderState.setState(ORDER_STATE_WAITING_PAY);
        log.debug("下单成功向状态表中写入支付状态:{}", orderState);
        rows= orderStateMapper.addOrderState(orderState);
        if (rows!=1){
            String message = "服务器繁忙，请稍后重试！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERROR_INSERT, message);
        }

        /*往订单数量表中添加或者修改数量*/
        HotelOrdersCount hotelOrdersCount=new HotelOrdersCount();
        HotelOrdersCountVO hotelOrdersCountVO =
                hotelOrdersCountMapper.getHotelOrderCountByHotelId(order.getHotelId());
        log.info("搜索出的订单的数量对象：{}",hotelOrdersCountVO);
        if (hotelOrdersCountVO==null){
            log.debug("酒店订单数量表中没有订单数据，所以执行添加方法，添加的酒店为：{}",order.getHotelName());
            hotelOrdersCount.setHotelName(order.getHotelName());
            hotelOrdersCount.setHotelId(order.getHotelId());
            hotelOrdersCount.setOrderCount(HOTEL_ORDERS_COUNT);
            log.debug("酒店订单数量表中没有订单数据，所以执行添加方法，" +
                    "添加的酒店为：{},修改的数据：{}",order.getHotelName(),hotelOrdersCount);
            int ordersCount = hotelOrdersCountMapper.addHotelOrdersCount(hotelOrdersCount);
            if (ordersCount!=1){
                String message = "服务器繁忙，请稍后重试！";
                log.warn(message);
                throw new ServiceException(ServiceCode.ERROR_INSERT, message);
            }
        }else {
            log.debug("酒店订单数量表中有该酒店订单数据，所以执行修改方法，修改的酒店为：{}",order.getHotelName());
            BeanUtils.copyProperties(hotelOrdersCountVO,hotelOrdersCount);
            hotelOrdersCount.setOrderCount(hotelOrdersCount.getOrderCount()+1);
            log.debug("酒店订单数量表中有该酒店订单数据，所以执行修改方法，" +
                    "修改的酒店为：{},修改的数据：{}",order.getHotelName(),hotelOrdersCount);
            int ordersCount = hotelOrdersCountMapper.updateHotelOrderCountByHotelId(hotelOrdersCount);
            if (ordersCount!=1){
                String message = "服务器繁忙，请稍后重试！";
                log.warn(message);
                throw new ServiceException(ServiceCode.ERROR_INSERT, message);
            }
        }


        List<HotelRoomNotesVO> hotelRoomNotesVOS =
                ordersMapper.getNotesByThreeColumn(ordersDTO.getHotelId(), ordersDTO.getRoomId(), list);
        log.debug("根据订单中的酒店ID：{}，房间ID：{}，住宿日期：{}，查询酒店房间记录表中的信息：{},查询结果的数量：{}"
                , ordersDTO.getHotelId(), ordersDTO.getRoomId(), list, hotelRoomNotesVOS, hotelRoomNotesVOS.size());

        /*创建集合存入查询结果中的日期*/
        List<LocalDateTime> dateTimes = new ArrayList<>();

        /*根据查询的结果对酒店房间记录表进行修改和增加*/
        if (hotelRoomNotesVOS == null) {
            log.debug("所增加的订单的日期记录表都没有，进入到第一种方式修改方式");
            /*查询结果如果为空则全部增加*/
            int count = 0;
            for (LocalDateTime localDateTime : list) {
                HotelRoomNotes hotelRoomNotes = new HotelRoomNotes();
                hotelRoomNotes.setHotelName(ordersDTO.getHotelName());
                hotelRoomNotes.setHotelId(ordersDTO.getHotelId());
                hotelRoomNotes.setRoomName(ordersDTO.getRoomName());
                hotelRoomNotes.setRoomId(ordersDTO.getRoomId());
                hotelRoomNotes.setCurrentDatetime(localDateTime);
                int number = hotelRoomInfoByHotelIdAndRoomId.getNumber();
                int buyRooms = order.getCountOfBuyRooms();
                int remainder = number - buyRooms;
                hotelRoomNotes.setRemainder(remainder);
                log.debug("酒店记录表中增加的数据：{}", hotelRoomNotes);
                ordersMapper.addHotelRoomNotes(hotelRoomNotes);
                count++;
            }
            if (count != list.size()) {
                String message = "服务器繁忙，请稍后重试！";
                log.warn(message);
                throw new ServiceException(ServiceCode.ERROR_INSERT, message);
            }
        } else if (hotelRoomNotesVOS.size() < days) {
            log.debug("所增加的订单的日期包含增加和修改的，进入到第二种方式修改方式");
            /*将查出来的时间放入dateTimes中*/
            for (HotelRoomNotesVO hotelRoomNotesVO : hotelRoomNotesVOS) {
                dateTimes.add(hotelRoomNotesVO.getCurrentDatetime());
            }
            log.debug("查询结果中已存在在的日期：{}", dateTimes);
            /*将list集合中和已经存在在记录表中的相同的日期移除
             * list剩下的应该是新增的，datetime中应该是修改的*/
            for (int i = 0; i < list.size(); i++) {
                for (LocalDateTime dateTime : dateTimes) {
                    if (dateTime.equals(list.get(i))) {
                        list.remove(i);
                    }
                }
            }
            log.debug("需要新增的日期记录数据：{}", list);
            int count = 0;
            for (LocalDateTime dateTime : dateTimes) {
                HotelRoomNotesVO singleNotesByThreeColumn = ordersMapper.getSingleNotesByThreeColumn(
                        order.getHotelId(), order.getRoomId(), dateTime
                );
                int oldRemainder = singleNotesByThreeColumn.getRemainder();
                int newRemainder = oldRemainder - order.getCountOfBuyRooms();
                ordersMapper.updateHotelRoomNotes(
                        newRemainder, singleNotesByThreeColumn.getHotelId(),
                        singleNotesByThreeColumn.getRoomId(), singleNotesByThreeColumn.getCurrentDatetime()
                );
                log.debug("根据订单中的酒店ID：{}，房间ID：{}，住宿日期：{}，修改酒店房间记录表中剩余房间数的信息：{}",
                        singleNotesByThreeColumn.getHotelId(), singleNotesByThreeColumn.getRoomId(),
                        singleNotesByThreeColumn.getCurrentDatetime(), newRemainder);
                count++;
            }
            if (count != dateTimes.size()) {
                String message = "服务器繁忙，请稍后重试！";
                log.warn(message);
                throw new ServiceException(ServiceCode.ERROR_INSERT, message);
            }
            int addCount = 0;
            for (LocalDateTime localDateTime : list) {
                HotelRoomNotes hotelRoomNotes = new HotelRoomNotes();
                hotelRoomNotes.setHotelName(ordersDTO.getHotelName());
                hotelRoomNotes.setHotelId(ordersDTO.getHotelId());
                hotelRoomNotes.setRoomName(ordersDTO.getRoomName());
                hotelRoomNotes.setRoomId(ordersDTO.getRoomId());
                hotelRoomNotes.setCurrentDatetime(localDateTime);
                int number = hotelRoomInfoByHotelIdAndRoomId.getNumber();
                int buyRooms = order.getCountOfBuyRooms();
                int remainder = number - buyRooms;
                hotelRoomNotes.setRemainder(remainder);
                log.debug("酒店记录表中增加的数据：{}", hotelRoomNotes);
                ordersMapper.addHotelRoomNotes(hotelRoomNotes);
                addCount++;
            }
            if (addCount != list.size()) {
                String message = "服务器繁忙，请稍后重试！";
                log.warn(message);
                throw new ServiceException(ServiceCode.ERROR_INSERT, message);
            }

        } else if (hotelRoomNotesVOS.size() == days) {
            log.debug("所增加的订单的日期记录表都有，进入到第三种方式修改方式");
            int count = 0;
            for (LocalDateTime localDateTime : list) {
                HotelRoomNotesVO singleNotesByThreeColumn = ordersMapper.getSingleNotesByThreeColumn(
                        order.getHotelId(), order.getRoomId(), localDateTime
                );
                int oldRemainder = singleNotesByThreeColumn.getRemainder();
                int newRemainder = oldRemainder - order.getCountOfBuyRooms();
                ordersMapper.updateHotelRoomNotes(
                        newRemainder, singleNotesByThreeColumn.getHotelId(),
                        singleNotesByThreeColumn.getRoomId(), singleNotesByThreeColumn.getCurrentDatetime()
                );
                log.debug("根据订单中的酒店ID：{}，房间ID：{}，住宿日期：{}，修改酒店房间记录表中剩余房间数的信息：{}",
                        singleNotesByThreeColumn.getHotelId(), singleNotesByThreeColumn.getRoomId(),
                        singleNotesByThreeColumn.getCurrentDatetime(), newRemainder);
                count++;
            }
            if (count != list.size()) {
                String message = "服务器繁忙，请稍后重试！";
                log.warn(message);
                throw new ServiceException(ServiceCode.ERROR_INSERT, message);
            }
        }

    }
    //TODO 回来设置业务，输入的日期不能小于现在的日期

    @Override
    public List<HotelCurrentRoomsVO> getCurrentRoomsByThreeColumn(HotelCurrentRoomsDTO hotelCurrentRoomsDTO) {
        /*计算天数*/
        HotelStandardVO hotel = hotelMapper.getHotelById(hotelCurrentRoomsDTO.getId());
        if (hotel == null) {
            String message = "酒店id不存在，查询失败！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERROR_NOT_FOUND, message);
        }
        Duration duration = Duration.between(
                hotelCurrentRoomsDTO.getCheckInTime(), hotelCurrentRoomsDTO.getDepartureTime());
        long days = duration.toDays();
        log.debug("计算出查询的天数：{}", days);

        List<LocalDateTime> currentTimeList = new ArrayList<>();

        for (long i = 0; i < days; i++) {
            LocalDateTime localDateTime = hotelCurrentRoomsDTO.getCheckInTime().plusHours(CHECK_IN_TIME_HOURS).plusDays(i);
            currentTimeList.add(localDateTime);
        }
        log.debug("获取住宿的日期：{}", currentTimeList);

        List<HotelRoomInfoVO> hotelRoomInfoByHotelId =
                hotelMapper.getHotelRoomInfoByHotelId(hotelCurrentRoomsDTO.getId());
        log.debug("获取查询酒店的房间基本信息：{}", hotelRoomInfoByHotelId);
        List<Long> roomIds = new ArrayList<>();

        for (HotelRoomInfoVO hotelRoomInfoVO : hotelRoomInfoByHotelId) {
            roomIds.add(hotelRoomInfoVO.getRoomId());
        }
        log.debug("获取查询的房间id：{}", roomIds);
        /*查询记录表中的数据*/
        List<HotelRoomNotesVO> minRemainderNotes = new ArrayList<>();

        for (Long roomId : roomIds) {

            List<HotelRoomNotesVO> result = new ArrayList<>();
            for (LocalDateTime currentTime : currentTimeList) {
                HotelRoomNotesVO singleNotesByThreeColumn = ordersMapper.getSingleNotesByThreeColumn(
                        hotelCurrentRoomsDTO.getId(), roomId, currentTime
                );
                if (singleNotesByThreeColumn != null) {
                    result.add(singleNotesByThreeColumn);
                }
            }
            log.debug("根据酒店ID：{}，房间ID：{}，对应的日期，查询对应的记录表信息：{}"
                    , hotelCurrentRoomsDTO.getId(), roomId, result);

            if (result != null) {
                int s = HOTEL_ROOM_NUMBER;
                for (int i = 0; i < result.size(); i++) {
                    if (s > result.get(i).getRemainder()) {
                        s = result.get(i).getRemainder();
                    }
                }
                log.debug("最小的剩余的数量：{}", s);
                for (HotelRoomNotesVO hotelRoomNotesVO : result) {
                    if (hotelRoomNotesVO.getRemainder() == s) {
                        minRemainderNotes.add(hotelRoomNotesVO);
                        break;
                    }
                }
                log.debug("输出记录的最小集合：{}", minRemainderNotes);
            }
        }

        log.debug("查询出剩余房间数最小的集合：{}", minRemainderNotes);

        List<HotelCurrentRoomsVO> rooms = new ArrayList<>();

        log.debug("开始执行返回数据的功能");
        List<Long> minRoomIDs = new ArrayList<>();
        for (HotelRoomNotesVO minRemainderNote : minRemainderNotes) {
            minRoomIDs.add(minRemainderNote.getRoomId());
        }
        log.debug("获取记录表中已经存在的房间id：{}", minRoomIDs);
        for (int i = 0; i < hotelRoomInfoByHotelId.size(); i++) {
            for (Long minRoomId : minRoomIDs) {
                if (minRoomId == hotelRoomInfoByHotelId.get(i).getRoomId()) {
                    hotelRoomInfoByHotelId.remove(i);
                }
            }
        }
        log.debug("移除了已存在记录表中的查询信息表中的数据的参数：{}", hotelRoomInfoByHotelId);
        for (HotelRoomInfoVO hotelRoomInfoVO : hotelRoomInfoByHotelId) {
            HotelCurrentRoomsVO room = new HotelCurrentRoomsVO();
            room.setHotelName(hotelRoomInfoVO.getHotelName());
            room.setHotelId(hotelRoomInfoVO.getHotelId());
            room.setRoomName(hotelRoomInfoVO.getRoomName());
            room.setRoomId(hotelRoomInfoVO.getRoomId());
            room.setRemainder(hotelRoomInfoVO.getNumber());
            room.setPrice(hotelRoomInfoVO.getPrice());
            rooms.add(room);
        }
        log.debug("第一次加入的数据：{}", rooms);
        for (HotelRoomNotesVO minRemainderNote : minRemainderNotes) {
            HotelRoomInfoVO minRoomInfo = hotelMapper.getHotelRoomInfoByHotelIdAndRoomId(
                    minRemainderNote.getHotelId(), minRemainderNote.getRoomId()
            );
            HotelCurrentRoomsVO room = new HotelCurrentRoomsVO();
            room.setHotelName(minRemainderNote.getHotelName());
            room.setHotelId(minRemainderNote.getHotelId());
            room.setRoomName(minRemainderNote.getRoomName());
            room.setRoomId(minRemainderNote.getRoomId());
            room.setRemainder(minRemainderNote.getRemainder());
            room.setPrice(minRoomInfo.getPrice());
            rooms.add(room);
        }
        log.debug("返回出客户端查询酒店房间数的数据：{}", rooms);
        if (rooms.size() != roomIds.size()) {
            String message = "服务器繁忙，请稍后重试！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERROR_SELECT, message);
        }
        return rooms;

    }

    /**
     * 查找带状态的UserOrdersListVO
     *
     * @param userId 用户id
     * @return 带状态的UserOrdersListVO
     */
    @Override
    public List<UserOrdersListVO> getUserOrdersList(Long userId) {
        List<UserOrdersListVO> userOrdersList = ordersMapper.getUserOrdersList(userId);

        //当下时间
        LocalDateTime nowTime = LocalDateTime.now();

        for (UserOrdersListVO userOrders : userOrdersList) {
            //入住时间
            LocalDateTime checkInTime = userOrders.getCheckInTime();
            //离店时间
            LocalDateTime departureTime = userOrders.getDepartureTime();

            /*赋值支付状态*/
            OrderStateVO orderStateVO =
                    orderStateMapper.getOrderStateByOrderId(userOrders.getId());
            userOrders.setOrderState(orderStateVO.getState());

            //判断该订单状态
            int checkInResult = checkInTime.compareTo(nowTime);
            int departureResult = departureTime.compareTo(nowTime);
            //如果离店时间比当下时间早,则订单状态为"已完成"
            if (departureResult < 0) {
                userOrders.setCurrentState(STATE[0]);
            }
            //如果入住时间比当下时间早或等于,并且离店时间比当下时间晚,则订单状态为"使用中"
            if (checkInResult <= 0 && departureResult > 0) {
                userOrders.setCurrentState(STATE[1]);
            }
            //如果入住时间比当下时间早或等于,并且离店时间比当下时间晚,则订单状态为"未使用"
            if (checkInResult >= 0) {
                userOrders.setCurrentState(STATE[2]);
            }

        }

        return userOrdersList;
    }

    @Override
    public void updateOrderStateByOrderId(Long orderId) {
        log.debug("开始处理【前台根据订单ID：{}，修改支付状态】的业务",orderId);
        OrderVO order = ordersMapper.getOrderById(orderId);
        if (order==null){
            String message = "订单不存在，请重新尝试！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERROR_NOT_FOUND, message);
        }
        int rows = orderStateMapper.updateOrderStateByOrderId(ORDER_STATE_HAD_PAY, orderId);
        if (rows!=1){
            String message = "服务器繁忙，请稍后重试！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERROR_UPDATE, message);
        }
    }

    @Override
    public OrderVO getLatestOrderById(Long userId) {
        log.debug("开始处理【前台根据用户id：{}查询最新订单信息】的业务",userId);
        UserStandardVO userStandardVO = userMapper.getStandardById(userId);
        if (userStandardVO==null){
            String message = "用户不存在，请先登录！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERROR_NOT_FOUND, message);
        }
        OrderVO orderVO = ordersMapper.getLatestOrderById(userId);
        return orderVO;
    }

    @Override
    public List<OrdersWithStateListVO> getAdminUserOrdersList() {
        log.debug("开始处理【后台获取订单列表】的业务");
        List<OrdersWithStateListVO> list = ordersMapper.getAdminUserOrdersList();
        log.debug("开始处理【后台获取订单列表】的业务,数据：{}",list);
        return list;
    }

    @Override
    public void cancelOrderOrDrawback(Long orderId,String function) {
        deleteOrDrawbackFunction(orderId,function);
    }

    @Override
    public void deleteAdminOrdersById(Long id) {
        log.debug("开始处理【后台根据订单Id：{}删除订单】的业务",id);
        deleteOrDrawbackFunction(id,ORDER_FUNCTION_DELETE_ORDER);
        log.debug("后台根据订单Id：{}删除订单完成",id);
        int rows = ordersMapper.deleteOrderState(id);
        if (rows!=1){
            String message = "服务器繁忙，请稍后重试！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERROR_DELETE, message);
        }

        rows = ordersMapper.deleteOrderById(id);
        if (rows!=1){
            String message = "服务器繁忙，请稍后重试！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERROR_DELETE, message);
        }
    }

    private void deleteOrDrawbackFunction(Long orderId,String function){
        log.debug("开始处理【前台根据订单id：{}，功能：{}，取消订单或者退款或者删除订单】的业务",orderId,function);
        if (!(ORDER_FUNCTION_DRAWBACK.equals(function) ||
                ORDER_FUNCTION_CANCEL_ORDER.equals(function)||
                ORDER_FUNCTION_DELETE_ORDER.equals(function))
        ){
            String message = "请求异常，请重新尝试！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERROR_BAD_REQUEST, message);
        }
        OrderVO orderVO = ordersMapper.getOrderById(orderId);
        if (orderVO==null){
            String message = "订单不存在，请稍后重试！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERROR_NOT_FOUND, message);
        }
        /*计算住宿天数*/
        Duration duration = Duration.between(orderVO.getCheckInTime(), orderVO.getDepartureTime());
        long days = duration.toDays();
        log.debug("计算出天数：{}",days);

        /*将所有天数装进集合里*/
        List<LocalDateTime> dateTimes=new ArrayList<>();
        for (long i = 0; i < days; i++) {
            LocalDateTime localDateTime=orderVO.getCheckInTime().plusDays(i);
            dateTimes.add(localDateTime);
        }
        log.debug("需要修改的天数集合：{}",dateTimes);
        int updateCount=0;
        int deleteCount=0;
        for (LocalDateTime dateTime : dateTimes) {
            /*根据以下三个参数查询HotelRoomNotes表中的数据*/
            HotelRoomNotesVO hotelRoomNotesVO =
                    ordersMapper.getSingleNotesByThreeColumn(orderVO.getHotelId(), orderVO.getRoomId(), dateTime);
            /*用户取消订单或者退款，导致余下房间数量变更，返回修改表中的余下房间数*/
            int remainder = orderVO.getCountOfBuyRooms() + hotelRoomNotesVO.getRemainder();

            /*如果天数等于10，不用修改，直接删除表中的数据*/
            if (remainder==HOTEL_ROOM_NUMBER) {
                log.debug("用户取消订单或者退款，当天余下房间数等于10，执行删除数据方法" +
                        "删除的表中的ID：{}",hotelRoomNotesVO.getId());
                int rows = ordersMapper.deleteHotelRoomsNotesById(hotelRoomNotesVO.getId());
                if (rows!=1){
                    String message = "服务器繁忙，请稍后重试！";
                    log.warn(message);
                    throw new ServiceException(ServiceCode.ERROR_DELETE, message);
                }
                deleteCount++;
                continue;
            }
            /*修改记录表中的数据，修改余下房间数*/
            ordersMapper.updateHotelRoomNotes(
                    remainder, orderVO.getHotelId(), orderVO.getRoomId(), dateTime);
            updateCount++;
        }
        int rows=updateCount+deleteCount;
        if (rows!=dateTimes.size()){
            String message = "服务器繁忙，请稍后重试！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERROR_DELETE, message);
        }
        if (ORDER_FUNCTION_DRAWBACK.equals(function)){
            rows = orderStateMapper.updateOrderStateByOrderId(ORDER_STATE_HAD_DRAWBACK, orderId);
            if (rows!=1){
                String message = "服务器繁忙，请稍后重试！";
                log.warn(message);
                throw new ServiceException(ServiceCode.ERROR_UPDATE, message);
            }
            return;
        }
        if (ORDER_FUNCTION_CANCEL_ORDER.equals(function)){
            rows = orderStateMapper.updateOrderStateByOrderId(ORDER_STATE_HAD_CANCEL_ORDER, orderId);
            if (rows!=1){
                String message = "服务器繁忙，请稍后重试！";
                log.warn(message);
                throw new ServiceException(ServiceCode.ERROR_UPDATE, message);
            }

        }
    }


}
